const amqp = require("amqplib");
const fs = require("fs");
const path = require("path");
async function updateFileNameInDBAndFS(id, newFileName) {
  const connection = await amqp.connect("amqp://localhost");
  const channel = await connection.createChannel();
  const queueName = "update_file_name_queue";
  await channel.assertQueue(queueName, { durable: false });
  const message = JSON.stringify({ id: id, newFileName: newFileName });
  // 发送消息到队列
  channel.sendToQueue(queueName, Buffer.from(message));
  console.log("已发送更新文件名的任务到消息队列");
  await channel.close();
  await connection.close();
}
// 消费者（用于处理数据库更新）
async function dbConsumer() {
  const connection = await amqp.connect("amqp://localhost");
  const channel = await connection.createChannel();
  const queueName = "update_file_name_queue";
  await channel.assertQueue(queueName, { durable: false });
  channel.consume(queueName, async (msg) => {
    if (msg) {
      const { id, newFileName } = JSON.parse(msg.content.toString());
      const { Database } = require("sqlite3").verbose();
      const db = new Database("your_database.db");
      const updateDBQuery = "UPDATE files SET filename =? WHERE id =?";
      db.run(updateDBQuery, [newFileName, id], function (err) {
        if (err) {
          console.error("数据库更新出错：", err);
        } else {
          console.log("数据库中文件名已成功更新");
          // 确认消息已处理
          channel.ack(msg);
        }
      });
    }
  });
}
// 消费者（用于处理文件系统更新）
async function fsConsumer() {
  const connection = await amqp.connect("amqp://localhost");
  const channel = await connection.createChannel();
  const queueName = "update_file_name_queue";
  await channel.assertQueue(queueName, { durable: false });
  channel.consume(queueName, async (msg) => {
    if (msg) {
      const { id, newFileName } = JSON.parse(msg.content.toString());
      // 获取旧文件名（假设之前有查询获取文件信息并存入变量fileInfo）
      const oldFileName = fileInfo.filename;
      const oldFilePath = path.join("your_file_directory", oldFileName);
      const newFilePath = path.join("your_file_directory", newFileName);
      // 修改文件系统中的文件名
      fs.rename(oldFilePath, newFilePath, function (renameError) {
        if (renameError) {
          console.error("文件系统更新出错：", renameError);
        } else {
          console.log("文件系统中文件名已成功更新");
          // 确认消息已处理
          channel.ack(msg);
        }
      });
    }
  });
}
module.exports = {
  updateFileNameInDBAndFS,
  dbConsumer,
  fsConsumer,
};
